<template>
  <el-card class="mt-10">
    <el-form
      label-width="100px"
      ref="skuFormRef"
      :model="skuFormDate"
      :rules="skuFormRules"
    >
      <el-form-item label="SPU名称">{{ spuStore.spuName }}</el-form-item>
      <el-form-item label="SKU名称" prop="skuName">
        <el-input placeholder="请输入SKU名称" v-model="skuFormDate.skuName" />
      </el-form-item>
      <el-form-item label="价格(元)" prop="price">
        <el-input-number
          class="sku-input-num"
          placeholder="请输入SKU价格"
          :min="0"
          :max="100000000"
          controls-position="right"
          v-model="skuFormDate.price"
        />
      </el-form-item>
      <el-form-item label="重量(千克)" prop="weight">
        <el-input-number
          class="sku-input-num"
          placeholder="请输入SKU重量"
          :min="0"
          :max="100000000"
          controls-position="right"
          v-model="skuFormDate.weight"
        />
      </el-form-item>
      <el-form-item label="规格描述" prop="skuDesc">
        <el-input
          :rows="3"
          type="textarea"
          placeholder="规格描述"
          v-model="skuFormDate.skuDesc"
        />
      </el-form-item>
      <el-form-item label="平台属性" prop="skuAttrValueList">
        <el-row :gutter="10" class="sku-row">
          <el-col
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            :xl="4.8"
            v-for="(attr, index) in attrList"
            :key="attr.id"
          >
            <div class="sku-div">
              <span class="sku-span">{{ attr.attrName }}</span>
              <el-select
                class="sku-select"
                v-model="skuFormDate.skuAttrValueList[index]"
              >
                <el-option
                  :label="attrValue.valueName"
                  :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
                  v-for="attrValue in attr.attrValueList"
                  :key="attrValue.id"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="销售属性" prop="skuSaleAttrValueList">
        <el-row :gutter="10" class="sku-row">
          <el-col
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            :xl="4.8"
            v-for="(saleAttr, index) in spuSaleAttrList"
            :key="saleAttr.id"
          >
            <div class="sku-div">
              <span class="sku-span">{{ saleAttr.saleAttrName }}</span>
              <el-select
                class="sku-select"
                v-model="skuFormDate.skuSaleAttrValueList[index]"
              >
                <el-option
                  :label="saleAttrValue.saleAttrValueName"
                  :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`"
                  v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                  :key="saleAttrValue.id"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="图片列表" prop="skuImageList">
        <el-table
          :data="spuImgList"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="60" />
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <el-image :src="row.imgUrl" class="sku-img" />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName" />
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-tag type="success" v-if="row.isDefault === '1'">默认</el-tag>
              <el-button
                type="primary"
                size="small"
                @click="setDefault(row)"
                v-else
              >
                设置默认
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addSkuAttr">保存</el-button>
        <el-button @click="emit('isShow', 1)">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "AddSku",
};
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import {
  getSpuImgListApi,
  getSpuSaleAttrListApi,
  postAddSkuApi,
} from "@/api/product/spu";
import { getAttrListApi } from "@/api/product/attr";
import { useSpuStore } from "@/stores/spu";
import { useCartgroyStroe } from "@/stores/cartgroy";
import type {
  SkuImageList,
  SpuSaleAttrList,
  Comment,
  SkuImageItem,
} from "@/api/product/model/spuModel";
import type { AttrList } from "@/api/product/model/attrModel";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";

// form表单实例
const skuFormRef = ref<FormInstance>();

// 自定义校验规则
const skuImgValidate = (rulea: any, value: SkuImageList, callback: any) => {
  if (!value.length) {
    callback(new Error("请选择商品图片"));
  }
  if (
    !value.some((item) => {
      return item.isDefault === "1";
    })
  ) {
    callback(new Error("请选择默认图片"));
  }
  callback();
};
// 校验规则
const skuFormRules = reactive<FormRules>({
  skuName: [{ required: true, message: "请输入SKU名称", trigger: "blur" }],
  price: [{ required: true, message: "请输入SKU价格", trigger: "blur" }],
  weight: [{ required: true, message: "请输入SKU重量", trigger: "blur" }],
  skuDesc: [{ required: true, message: "请输入SKU描述", trigger: "blur" }],
  skuAttrValueList: [{ required: true, message: "请选择平台属性" }],
  skuSaleAttrValueList: [{ required: true, message: "请选择销售属性" }],
  skuImageList: [{ required: true, validator: skuImgValidate }],
});

// 原始属性
const skuFormDate = reactive<Comment>({
  skuName: "",
  price: 0,
  weight: 0,
  skuDesc: "",
  skuAttrValueList: [
    // {
    //   attrId: 0,
    //   attrName: "string",
    //   id: 0,
    //   skuId: 0,
    //   valueId: 0,
    //   valueName: "string",
    // },
  ],
  skuSaleAttrValueList: [
    // {
    //   id: 0,
    //   saleAttrId: 0,
    //   saleAttrName: "string",
    //   saleAttrValueId: 0,
    //   saleAttrValueName: "string",
    //   skuId: 0,
    //   spuId: 0,
    // },
  ],
  skuImageList: [
    // {
    //   id: 0,
    //   imgName: "string",
    //   imgUrl: "string",
    //   isDefault: "string",
    //   skuId: 0,
    //   spuImgId: 0,
    // },
  ],
  skuDefaultImg: "",
});

const spuImgList = ref<SkuImageList>([]);
const spuSaleAttrList = ref<SpuSaleAttrList>([]);
const attrList = ref<AttrList>([]);

const emit = defineEmits(["isShow"]);

const spuStore = useSpuStore();

const handleSelectionChange = (val: SkuImageList) => {
  skuFormDate.skuImageList = val;
};

// 保存发送请求
const addSkuAttr = async () => {
  await skuFormRef.value?.validate();
  await postAddSkuApi({
    ...skuFormDate,
    category3Id: cartGroyStore.cartgroy3Id as number,
    skuSaleAttrValueList: skuFormDate.skuSaleAttrValueList
      .filter(Boolean)
      .map((item) => {
        const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] = (
          item as string
        ).split(":");
        return {
          saleAttrId: +saleAttrId,
          saleAttrName,
          saleAttrValueId: +saleAttrValueId,
          saleAttrValueName,
        };
      }),
    skuAttrValueList: skuFormDate.skuAttrValueList
      .filter(Boolean)
      .map((item) => {
        const [attrId, attrName, valueId, valueName] = (item as string).split(
          ":"
        );
        return {
          attrId: +attrId,
          attrName,
          valueId: +valueId,
          valueName,
        };
      }),
    spuId: spuStore.id as number,
  });
  ElMessage.success("添加SKU成功");
  emit("isShow", 1);
};
onMounted(async () => {
  spuImgList.value = await getSpuImgListApi(spuStore.id as number);
  spuImgList.value.forEach((item) => {
    item.isDefault = "0";
  });
});
onMounted(async () => {
  spuSaleAttrList.value = await getSpuSaleAttrListApi(spuStore.id as number);
});

const cartGroyStore = useCartgroyStroe();
onMounted(async () => {
  const { cartgroy1Id, cartgroy2Id, cartgroy3Id } = cartGroyStore;
  attrList.value = await getAttrListApi({
    cartgroy1Id: cartgroy1Id as number,
    cartgroy2Id: cartgroy2Id as number,
    cartgroy3Id: cartgroy3Id as number,
  });
});

// 修改默认
const setDefault = (row: SkuImageItem) => {
  skuFormRef.value?.clearValidate(["skuImageList"]);
  spuImgList.value.map((item) => {
    return (item.isDefault = "0");
  });
  row.isDefault = "1";
  skuFormDate.skuDefaultImg = row.imgUrl;
};
</script>

<style scoped>
.sku-input-num,
.sku-row {
  width: 100%;
}
.sku-input-num :deep(.el-input__inner) {
  text-align: left;
}
.sku-div {
  display: flex;
}
.sku-span {
  width: 80px;
  text-align: right;
}
.sku-select {
  margin-left: 10px;
  margin-bottom: 10px;
  flex: 1;
}
.sku-img {
  width: 100px;
  height: 100px;
}
</style>
